/**
 * VIP页面JavaScript
 */

// VIP页面管理器
window.VipManager = {
    // VIP数据
    vipData: null,

    // 初始化
    init(data) {
        this.vipData = data || {};
        this.initVipPage();
        this.bindEvents();
    },

    // 绑定事件
    bindEvents() {
        // 绑定全局函数
        window.scrollToPackages = () => this.scrollToPackages();
        window.buyVip = (packageId, packageName, price) => this.buyVip(packageId, packageName, price);
    },

    // 初始化VIP页面
    initVipPage() {
        // 动态调整套餐网格列数
        const packagesCount = this.vipData.vip_packages ? this.vipData.vip_packages.length : 3;
        const gridClass = packagesCount <= 3 ? `md:grid-cols-${packagesCount}` : 'md:grid-cols-3';
        $('#packages-grid').removeClass().addClass(`grid grid-cols-1 ${gridClass} gap-6`);
    },

    // 滚动到套餐区域
    scrollToPackages() {
        document.getElementById('vip-packages')?.scrollIntoView({
            behavior: 'smooth'
        });
    },

    // 购买VIP
    buyVip(packageId, packageName, price) {
        // 检查登录状态
        if (!window.userState || !window.userState.isLogin) {
            showWarning('请先登录后再购买VIP', 2500);
            setTimeout(() => {
                if (typeof openLoginModal === 'function') {
                    openLoginModal(window.location.href);
                } else {
                    window.location.href = '/login?redirect=' + encodeURIComponent(window.location.href);
                }
            }, 1000);
            return;
        }

        // 显示购买确认
        this.showBuyConfirm(packageId, packageName, price);
    },

    // 显示购买确认
    showBuyConfirm(packageId, packageName, price) {
        // 创建购买确认弹窗
        const modalHtml = `
            <div id="vip-buy-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50" onclick="this.remove()">
                <div class="bg-white rounded-lg p-6 max-w-md w-full mx-4" onclick="event.stopPropagation()">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-medium text-gray-900">确认购买VIP</h3>
                        <button onclick="document.getElementById('vip-buy-modal').remove()" class="text-gray-400 hover:text-gray-600">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>

                    <div class="mb-6">
                        <div class="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-4">
                            <h4 class="font-medium text-blue-900 mb-2">${packageName}</h4>
                            <p class="text-2xl font-bold text-blue-600">¥${price}</p>
                        </div>

                        <div class="space-y-3">
                            <h5 class="font-medium text-gray-700">选择支付方式：</h5>
                            <div id="payment-channels" class="space-y-2">
                                <!-- 支付渠道将在这里动态加载 -->
                            </div>
                        </div>
                    </div>

                    <div class="flex space-x-3">
                        <button onclick="document.getElementById('vip-buy-modal').remove()"
                                class="flex-1 bg-gray-200 text-gray-800 py-2 px-4 rounded-lg hover:bg-gray-300 transition-colors">
                            取消
                        </button>
                        <button onclick="VipManager.confirmBuyVip(${packageId})"
                                class="flex-1 bg-blue-500 text-white py-2 px-4 rounded-lg hover:bg-blue-600 transition-colors">
                            确认购买
                        </button>
                    </div>
                </div>
            </div>
        `;

        $('body').append(modalHtml);

        // 加载支付渠道
        this.loadPaymentChannels();
    },

    // 加载支付渠道
    loadPaymentChannels() {
        $.ajax({
            url: '/web/user/getPaymentChannels',
            type: 'POST',
            dataType: 'json',
            success: (response) => {
                let channelsHtml = '';
                const channelsContainer = $('#payment-channels');
                response.data.forEach((channel, index) => {
                    channelsHtml += `
                        <label class="flex items-center p-3 border border-gray-200 rounded-lg cursor-pointer hover:bg-gray-50 transition-colors">
                            <input type="radio" name="payment_channel" value="${channel.channel_id}" ${index === 0 ? 'checked' : ''} class="mr-3">
                            <img src="${channel.ico}" alt="${channel.show_name}" class="w-6 h-6 mr-3">
                            <span class="font-medium">${channel.show_name}</span>
                        </label>
                    `;
                });
                channelsContainer.html(channelsHtml);
            }
        });
    },

    // 确认购买VIP
    confirmBuyVip(packageId) {
        const selectedChannel = $('input[name="payment_channel"]:checked').val();
        if (!selectedChannel) {
            showError('请选择支付方式');
            return;
        }

        // 关闭弹窗
        $('#vip-buy-modal').remove();

        // 处理购买
        this.processBuyVip(packageId, selectedChannel);
    },

    // 处理VIP购买
    processBuyVip(packageId, channelId = null) {
        // 显示加载提示
        // showInfo('正在创建订单...', 2000);

        // 调用Web端购买接口
        $.ajax({
            url: '/web/user/buyVip',
            type: 'POST',
            data: {
                vip_id: packageId,
                channel_id: channelId
            },
            dataType: 'json',
            success: (response) => {
                if (response.code === 1) {
                    showSuccess('订单创建成功', 2000);

                    // 跳转到支付页面
                    const payUrl = response.data.pay_url;

                    // 显示支付结果弹窗
                    this.showPaymentResult(response.data.order_id, payUrl);
                } else {
                    showError(response.msg || '创建订单失败', 3000);
                }
            },
            error: (xhr) => {
                let errorMsg = '网络连接失败，请稍后重试';
                if (xhr.responseJSON && xhr.responseJSON.msg) {
                    errorMsg = xhr.responseJSON.msg;
                }
                showError(errorMsg, 3000);
            }
        });
    },

    // 显示支付结果弹窗
    showPaymentResult(orderId, payUrl) {
        const modalHtml = `
            <div id="payment-result-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
                <div class="bg-white rounded-lg p-6 max-w-md w-full mx-4">
                    <div class="text-center mb-6">
                        <div class="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-4">
                            <i class="fas fa-credit-card text-blue-500 text-2xl"></i>
                        </div>
                        <h3 class="text-lg font-medium text-gray-900 mb-2">订单创建成功</h3>
                        <p class="text-gray-600">订单号：${orderId}</p>
                    </div>

                    <div class="space-y-3">
                        <button onclick="window.open('${payUrl}', '_blank')"
                                class="w-full bg-blue-500 text-white py-3 px-4 rounded-lg hover:bg-blue-600 transition-colors">
                            <i class="fas fa-external-link-alt mr-2"></i>前往支付
                        </button>
                        <button onclick="VipManager.checkPaymentStatus('${orderId}')"
                                class="w-full bg-green-500 text-white py-3 px-4 rounded-lg hover:bg-green-600 transition-colors">
                            <i class="fas fa-check mr-2"></i>我已完成支付
                        </button>
                        <button onclick="VipManager.copyOrderId('${orderId}')"
                                class="w-full bg-gray-200 text-gray-800 py-3 px-4 rounded-lg hover:bg-gray-300 transition-colors">
                            <i class="fas fa-copy mr-2"></i>复制订单号
                        </button>
                    </div>
                </div>
            </div>
        `;

        $('body').append(modalHtml);
    },

    // 检查支付状态
    checkPaymentStatus(orderId) {
        // showInfo('正在检查支付状态...', 2000);

        $.ajax({
            url: '/web/user/checkPaymentStatus',
            type: 'POST',
            data: { order_id: orderId },
            dataType: 'json',
            success: (response) => {
                if (response.code === 1) {
                    if (response.data.paid) {
                        showSuccess('支付成功！VIP已开通', 3000);
                        $('#payment-result-modal').remove();
                        // 刷新页面显示最新VIP状态
                        setTimeout(() => {
                            window.location.reload();
                        }, 1500);
                    } else {
                        showWarning('订单尚未支付，请完成支付后再试', 3000);
                    }
                } else {
                    showError(response.msg || '检查支付状态失败', 3000);
                }
            },
            error: () => {
                showError('网络连接失败，请稍后重试', 3000);
            }
        });
    },

    // 复制订单号
    copyOrderId(orderId) {
        if (navigator.clipboard) {
            navigator.clipboard.writeText(orderId).then(() => {
                showSuccess('订单号已复制到剪贴板', 2000);
            }).catch(() => {
                this.fallbackCopyOrderId(orderId);
            });
        } else {
            this.fallbackCopyOrderId(orderId);
        }
    },

    // 降级复制方法
    fallbackCopyOrderId(orderId) {
        const textArea = document.createElement('textarea');
        textArea.value = orderId;
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();

        try {
            document.execCommand('copy');
            showSuccess('订单号已复制到剪贴板', 2000);
        } catch (err) {
            showError('复制失败，请手动复制：' + orderId, 5000);
        }

        document.body.removeChild(textArea);
    },
};
$(document).ready(function () {
    // 初始化VIP页面
    if (typeof VipManager !== 'undefined') {
        VipManager.init();
    }
});